﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Diagnostics;

namespace Utilities
{
    public class Utils
    {
        public static string EncodeHTMLString(string str)
        {
            Dictionary<char, string> replaceDict = new Dictionary<char, string>();
            replaceDict.Add('\'', "&#39;");
            replaceDict.Add('&', "&amp;");
            //replaceDict.Add('"', "&quot;");
            replaceDict.Add('"', "");
            replaceDict.Add('<', "&lt;");
            replaceDict.Add('>', "&gt;");
            replaceDict.Add('/', "&frasl;");
            foreach (char key in replaceDict.Keys)
            {
                if (str.IndexOf(key) != -1) str = str.Replace(key.ToString(), replaceDict[key]);
            }
            /*
            if (str.IndexOf("'") != -1)
                str = str.Replace("'", "");
            */
            str = HttpUtility.HtmlEncode(str);
            return str;
        }

        public static string formatTextJs(string str)
        {
            Dictionary<char, string> replaceDict = new Dictionary<char, string>();
            replaceDict.Add('\'', "");
            replaceDict.Add('"', "");
            foreach (char key in replaceDict.Keys)
            {
                if (str.IndexOf(key) != -1) str = str.Replace(key.ToString(), replaceDict[key]);
            }
            /*
            if (str.IndexOf("'") != -1)
                str = str.Replace("'", "");
            */
            return str;
        }

        public static void Set_Page_FB(System.Web.UI.Page __Page, string addUrl, string addTitle, string addImg, string addDesc)
        {
            addTitle = addTitle.Replace("'", "");
            //addTitle += PublicConstants.SuffixTitle;

            System.Web.UI.HtmlControls.HtmlMeta __ctlUrl = __Page.Header.FindControl("idOgUrl") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlUrl != null)
            {
                __ctlUrl.Attributes["content"] = addUrl != "" ? addUrl : "";
            }

            System.Web.UI.HtmlControls.HtmlMeta __ctlTitle = __Page.Header.FindControl("idOgIitle") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlTitle != null)
            {
                __ctlTitle.Attributes["content"] = addTitle != "" ? addTitle : "";
            }

            System.Web.UI.HtmlControls.HtmlMeta __ctlImg = __Page.Header.FindControl("idOgImg") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlImg != null)
            {
                __ctlImg.Attributes["content"] = addImg != "" ? addImg : "";
            }

            System.Web.UI.HtmlControls.HtmlMeta __ctrlDesc = __Page.Header.FindControl("idOgDesc") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctrlDesc != null)
            {
                __ctrlDesc.Attributes["content"] = addDesc;
            }
        }

        #region Get QueryString

        public static string GetQuery(string name, string val)
        {
            var context = HttpContext.Current;
            return !string.IsNullOrEmpty(context.Request.QueryString[name]) ? context.Request.QueryString[name].Trim() : val;
        }
        public static byte GetQuery(string name, byte val)
        {
            var context = HttpContext.Current;
            return !string.IsNullOrEmpty(context.Request.QueryString[name]) ? byte.Parse(context.Request.QueryString[name].Trim()) : val;
        }
        public static int GetQuery(string name, int val)
        {
            var context = HttpContext.Current;
            return !string.IsNullOrEmpty(context.Request.QueryString[name]) ? int.Parse(context.Request.QueryString[name].Trim()) : val;
        }
        public static long GetQuery(string name, long val)
        {
            var context = HttpContext.Current;
            return !string.IsNullOrEmpty(context.Request.QueryString[name]) ? long.Parse(context.Request.QueryString[name].Trim()) : val;
        }
        public static bool GetQuery(string name, bool val)
        {
            var context = HttpContext.Current;
            return !string.IsNullOrEmpty(context.Request.QueryString[name]) ? bool.Parse(context.Request.QueryString[name].Trim()) : val;
        }

        #endregion

        public static string MD5Encrypt(string plainText)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(plainText);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    ret += a.ToString("x2");
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }

        public static string GetCurrentCmsPage()
        {
            return "/BackEnd/" + HttpContext.Current.Request.Url.Query;
        }

        #region Get Upload Folder

        public static string GetUploadForAvatarUser()
        {
            return Constant.InUserAvatarPath;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="boxtype">0: box san pham, 1 box tin tuc</param>
        /// <returns></returns>
        public static string GetUploadForAvatarBox(int boxtype)
        {
            const string format = "yyyy/MM/";
            if(boxtype==1)
                return Constant.BoxNewsAvatarPath + DateTime.Now.ToString(format);
            return Constant.BoxProductAvatarPath + DateTime.Now.ToString(format);
        }

        public static string GetUploadForAvatarProduct()
        {
            const string format = "yyyy/MM/";
            return Constant.ProductAvatarPath + DateTime.Now.ToString(format);
        }

        public static string GetUploadForAvatarNew()
        {
            const string format = "yyyy/MM/";
            return Constant.NewAvatarPath + DateTime.Now.ToString(format);
        }

        public static string GenerateFileName(string extention)
        {
            const string format = "yyyyMMddHHmmssFFFF";
            return DateTime.Now.ToString(format) + extention;
        }

        public static string GenerateAvatarName(string extention)
        {
            const string format = "ddHHmmssFFFF";
            return DateTime.Now.ToString(format) + extention;
        }

        /// <summary>
        /// Type: 0:Product; 1:News
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetUploadForGallery(int type, int id)
        {
            if (type==0) return Constant.GalleryAvatarPath + "product/" + id.ToString() + "/";
            return Constant.GalleryAvatarPath + "news/" + id.ToString() + "/";
        }

        #endregion

        //Tạo file trong chương trình
        public static bool CreateFile(string strFilename, string strContent)
        {
            bool functionReturnValue = false;
            try
            {
                functionReturnValue = false;
                //Kiểm tra sự tồn tại của thư mục
                if (!System.IO.Directory.Exists(Left(strFilename, strFilename.LastIndexOf("\\", strFilename.Length))))
                {
                    //Tạo thư mục
                    System.IO.Directory.CreateDirectory(Left(strFilename, strFilename.LastIndexOf("\\", strFilename.Length)));
                }

                System.IO.StreamWriter sFileCreate = new System.IO.StreamWriter(strFilename);
                sFileCreate.WriteLine(strContent);
                sFileCreate.Close();
                functionReturnValue = true;
                return functionReturnValue;
            }
            catch (Exception exp)
            {
                Logger.WriteLog(Logger.LogType.Error,
                                "File: " + (new StackTrace().GetFrame(0).GetMethod().DeclaringType.Name) +
                                " --- Function: " + (new StackTrace().GetFrame(0).GetMethod().Name) +
                                " --- Mess: " + exp.ToString());
            }
            return functionReturnValue;
        }

        public static string Left(string s, int left)
        {
            return s.Substring(0, left);
        }

        public static Boolean StringToBoolean(string str)
        {
            if (str == "1")
                return true;
            else
                return false;
        }
    }
}
